package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.exceptions.LyException;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> querySpecGroupByCategoryId(Long categoryId) {
        List<SpecGroup> specGroupList = query().eq("category_id", categoryId).list();
        return SpecGroupDTO.convertEntityList(specGroupList);
    }

    @Override
    public List<SpecGroupDTO> querySpecDetailByCategoryId(Long categoryId) {
        List<SpecGroupDTO> groupDTOList = querySpecGroupByCategoryId(categoryId);
        if (CollectionUtils.isEmpty(groupDTOList)) {
            throw new LyException(404, "商品规格组不存在");
        }
//  1.      for(SpecGroupDTO groupDTO : groupDTOList){
//            Long id = groupDTO.getId();
//            List<SpecParamDTO> paramDTOS = paramService.queryParams(null, id, null);
//            groupDTO.setParams(paramDTOS);
//        }
        List<SpecParamDTO> paramList = paramService.querySpecParam(categoryId, null, null);
        Map<Long, List<SpecParamDTO>> map = paramList.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
//  2.      Map<Long,List<SpecParamDTO>> map = new HashMap<>();
//        for (SpecParamDTO paramDTO : paramList) {
//            Long groupId = paramDTO.getGroupId();
//            //判断在map中是否存在
//            if (!map.containsKey(groupId)){
//                //不存在，就新建list
//                map.put(groupId,new ArrayList<>());
//                //把paramDTO 放入list
//                map.get(groupId).add(paramDTO);
//            }else {
//                //已经存在，存入list
//                map.get(groupId).add(paramDTO);
//            }
//        }
        for (SpecGroupDTO groupDTO : groupDTOList) {
            Long id = groupDTO.getId();
            List<SpecParamDTO> list = map.get(id);
            groupDTO.setParams(list);
        }
        return groupDTOList;
    }



}